﻿using Consul;
using iS3.Server.Core.Filter;
using iS3.Server.Core.Swagger;
using Microsoft.Owin.Cors;
using Owin;
using Swashbuckle.Application;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net.Http.Formatting;
using System.Text;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Cors;
using IdentityServer4.AccessTokenValidation;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Owin.Security.OpenIdConnect;
using NetMQ;
using NetMQ.Sockets;
using System.Configuration;
using iS3.Server.Core.NetMQ;

namespace iS3.Server.Core
{
    public class Startup
    {
        public void Configuration(IAppBuilder appBuilder)
        {
            HttpConfiguration config = new HttpConfiguration();
            config.EnableCors(new EnableCorsAttribute("*", "*", "*"));
            config.MapHttpAttributeRoutes();
            config.Routes.MapHttpRoute("token", "token", new { });
            config.Routes.MapHttpRoute(name: "ActionApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional });
            config.Routes.MapHttpRoute("API Default", "api/{controller}/{id}", new { id = RouteParameter.Optional });
            config.Routes.MapHttpRoute("API universal", "api/{controller}/{domain}/{type}/{id}", new { id = RouteParameter.Optional, domain=RouteParameter.Optional,type=RouteParameter.Optional });
            config.Formatters
              .XmlFormatter.SupportedMediaTypes.Clear();

            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(
                                new Newtonsoft.Json.Converters.IsoDateTimeConverter()
                                {
                                    DateTimeFormat = "yyyy-MM-dd HH:mm:ss"
                                }
                );
            config.Formatters.JsonFormatter.SerializerSettings.Converters.Add(new IdToStringConverter());
            //默认返回 json
            config.Formatters
                .JsonFormatter.MediaTypeMappings.Add(
                new QueryStringMapping("datatype", "json", "application/json"));


            // Filter Config
            config.Filters.Add(new ResponseFilterAttribute());
            config.Filters.Add(new ApiErrorHandleAttribute());

            SwaggerConfig.Register(config);



            //

            appBuilder.UseCors(CorsOptions.AllowAll);
            
            //ConfigureOAuth(appBuilder);

            //大文件
            //GlobalConfiguration.Configuration.Services.Replace(typeof(IHostBufferPolicySelector), new NoBufferPolicySelector());

            try
            {
                using (var consulClient = new ConsulClient(ConsulManager.consulConfig))
                {
                    AgentServiceRegistration asr = new AgentServiceRegistration();
                    asr.Address = ConsulManager.ip;
                    asr.Port = Convert.ToInt32(ConsulManager.port);
                    asr.ID = ConsulManager.serviceId;
                    asr.Name = ConsulManager.serviceName;
                    asr.Check = new AgentServiceCheck()
                    {
                        DeregisterCriticalServiceAfter = TimeSpan.FromSeconds(5),
                        HTTP = $"http://{ConsulManager.ip}:{ConsulManager.port}/api/Health",
                        Interval = TimeSpan.FromSeconds(10),
                        Timeout = TimeSpan.FromSeconds(5)
                    };
                    consulClient.Agent.ServiceRegister(asr).Wait();
                    Console.WriteLine(string.Format("success connect to consul at {0}", ConsulManager.consulConfig.Address));
                };
            }
            catch (Exception ex)
            {
                Console.WriteLine("warning:无法连接consul");
            }


            //netmq

            NetMQManager.getInstance().initClient();

            //

            appBuilder.MapSignalR();   //signalr


            appBuilder.UseWebApi(config);

            config.EnsureInitialized();
        }
        //public void ConfigureOAuth(IAppBuilder app)
        //{
        //    OAuthAuthorizationServerOptions OAuthServerOptions = new OAuthAuthorizationServerOptions()
        //    {
        //        AllowInsecureHttp = true,
        //        TokenEndpointPath = new PathString("/token"),
        //        AccessTokenExpireTimeSpan = TimeSpan.FromDays(14),
        //        Provider = new SimpleAuthorizationServerProvider(),

        //        refresh token provider
        //        RefreshTokenProvider = new SimpleRefreshTokenProvider()
        //    };

        //    Token Generation
        //    app.UseOAuthAuthorizationServer(OAuthServerOptions);
        //    app.UseOAuthBearerAuthentication(new OAuthBearerAuthenticationOptions());
        //}
    }
}
